<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');

class Edit_profil extends CI_Controller{
	var $_public_view;

	function __construct(){
		parent::__construct();
		$this->load->helper(array('form', 'url','html'));
        $this->load->model('model_user', 'muser');
        $this->load->library('session');
        $this->config->load('ojexcom');
        $this->_public_view = $this->config->item('public_view');
	}

	function index(){
		 //cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

		$data = array(
            //'detail' => $this->muser->get_user_trip_detail($str_id),
            'output' => get(),
            'page_title' => 'Update Profil',
            'isLogin' => $isLogin, 'user' => $user, 'id' => $id,
            'page_content' => 'update_profil');
       $this->load->view($this->_public_view, $data);
	}

	function get(){
		//cek session
        $isLogin = $this->session->userdata('isLogin');
        $user = ''; $id='';
        if ($isLogin) {
            $user = $this->session->userdata('username');
            $id = $this->session->userdata('user_id');
        }

        //cek segment
        $str_id = '';
        if ($this->uri->segment(2) == FALSE) {
            redirect('home', 'location');
        } else {
            $str_id = $this->uri->segment(3);
        }

		$data_output['success'] = "false";
		$userid = $str_id;
        $myid = $id;
		$myStatus = $this->input->post('myStatus');
		$query_user = $this->db->query("SELECT username, name,password,isPremium,entryDate,lastUpdated,avatar,lastUpdatedAvatar,gender, (SELECT SUM(rateValue)/COUNT(rateValue) FROM rating WHERE providerId = ".$userid." AND rateValue >0) AS rate, (SELECT COUNT(rateValue) FROM rating WHERE providerId = ".$userid." AND rateValue >0) AS voterCount FROM `user` WHERE `id` = '".$userid."'");
		$row_user = $query_user->row();
		if($query_user->num_rows() > 0){
			$data_output['success'] = "true";
			$data_output['username'] = $row_user->username;
			$data_output['name'] = $row_user->name;
			$data_output['isPremium'] = $row_user->isPremium;
			$data_output['entryDate'] = $row_user->entryDate;
			$data_output['lastUpdated'] = $row_user->lastUpdated;
			$data_output['avatar'] = $row_user->avatar;
			$data_output['lastUpdatedAvatar'] = $row_user->lastUpdatedAvatar;
			$data_output['gender'] = $row_user->gender;
			$data_output['rate'] = "".$row_user->rate;
			$data_output['voterCount'] = "".$row_user->voterCount;

			$query_userprofile = $this->db->query("SELECT phoneNumber,bio,address,avatarMotor,lastUpdatedAvatarMotor,motorDesc,motorYear,licenseNumber,deliverCounter,email FROM `userprofile` WHERE `idUser` = '".$userid."'");
			$row_userprofile = $query_userprofile->row();
			$data_output['phoneNumber'] = $row_userprofile->phoneNumber;
			$data_output['bio'] = $row_userprofile->bio;
			$data_output['address'] = $row_userprofile->address;
			$data_output['avatarMotor'] = $row_userprofile->avatarMotor;
			$data_output['lastUpdatedAvatarMotor'] = $row_userprofile->lastUpdatedAvatarMotor;
			$data_output['licenseNumber'] = $row_userprofile->licenseNumber;
			$data_output['motorDesc'] = $row_userprofile->motorDesc;
			$data_output['motorYear'] = $row_userprofile->motorYear;
			$data_output['deliverCounter'] = $row_userprofile->deliverCounter;
			$data_output['email'] = $row_userprofile->email;
		}
		
		$query = $this->db->query("SELECT t.* FROM trip t JOIN `user` u ON u.id=t.userId WHERE departTime >= '".date("Y-m-d H:i:s")."' AND userId = ".$userid." AND t.is_available=1 ORDER BY departTime LIMIT 1");
		if($query->num_rows() < 1){
			$data_output['currentTrip'] = "";
		}else{
			$row = $query->row(); 
			$data_output["currentTrip"][0]["id"] = $row->id;
			$data_output["currentTrip"][0]["status"] = $row->status;
			$data_output["currentTrip"][0]["source_label"] = $row->source_label;
			$data_output["currentTrip"][0]["source_latitude"] = $row->source_latitude;
			$data_output["currentTrip"][0]["source_longitude"] = $row->source_longitude;
			$data_output["currentTrip"][0]["destination_label"] = $row->destination_label;
			$data_output["currentTrip"][0]["destination_latitude"] = $row->destination_latitude;
			$data_output["currentTrip"][0]["destination_longitude"] = $row->destination_longitude;
			$data_output["currentTrip"][0]["via"] = $row->via;
			$data_output["currentTrip"][0]["priceInRupiah"] = $row->priceInRupiah;
			$data_output["currentTrip"][0]["priceInPoint"] = $row->priceInPoint;
			$data_output["currentTrip"][0]["departTime"] = $row->departTime;
			$data_output["currentTrip"][0]["notes"] = $row->notes;
			if($row->status == 'P' && $myid != $userid)				$data_output["pickUpStatus"] = $this->getPickupStatus($myid,$userid);
		}
		
		
		$privacy_criteria = " AND t.privacy = 0";
		if($myid === $userid)			$privacy_criteria = "";

		$query = $this->db->query("SELECT COUNT(*) AS historyCount FROM `transaction` t JOIN transactionStatus s ON t.id=s.idTransaction WHERE s.`status` = 'F' AND (userId = ".$userid." OR providerId = ".$userid.")".$privacy_criteria.' ORDER BY t.id DESC LIMIT 3');
		$row = $query->row();
		$historyCount = $row->historyCount;
		$data_output["viewMoreHistory"] = "false";
		$data_output['history'] = "";
		if($historyCount > 0){
			if($historyCount > 3){
				$data_output["viewMoreHistory"] = "true";
			}
			$query = $this->db->query("SELECT DISTINCT t.* FROM `transaction` t JOIN transactionStatus s ON t.id=s.idTransaction WHERE s.`status` = 'F' AND (userId = ".$userid." OR providerId = ".$userid.")".$privacy_criteria.' ORDER BY t.id DESC LIMIT 3');
			$row = $query->row();
			if($query->num_rows() < 1 || $historyCount < 1){
				$data_output['history'] = "";
			}else{
				$count = 0;
				foreach($query->result() as $row){
					$data_output["history"][$count]["id"] = $row->id;
					$data_output["history"][$count]["departTime"] = $row->departTime;
					$data_output["history"][$count]["userId"] = $row->userId;
					$data_output["history"][$count]["name"] = $this->getNameById($row->userId);
					$data_output["history"][$count]["avatar"] = $this->getAvatarById($row->userId);
					$data_output["history"][$count]["lastUpdatedAvatar"] = $this->getLastUpdatedAvatar($row->userId);
					$data_output["history"][$count]["providerId"] = $row->providerId;
					$data_output["history"][$count]["providerName"] = $this->getNameById($row->providerId);
					$data_output["history"][$count]["providerAvatar"] = $this->getAvatarById($row->providerId);
					$data_output["history"][$count]["providerLastUpdatedAvatar"] = $this->getLastUpdatedAvatar($row->providerId);
					$data_output["history"][$count]["source_label"] = $row->source_label;
					$data_output["history"][$count]["source_latitude"] = $row->source_latitude;
					$data_output["history"][$count]["source_longitude"] = $row->source_longitude;
					$data_output["history"][$count]["destination_label"] = $row->destination_label;
					$data_output["history"][$count]["destination_latitude"] = $row->destination_latitude;
					$data_output["history"][$count]["destination_longitude"] = $row->destination_longitude;
					$data_output["history"][$count]["paymentMethod"] = $row->paymentMethod;
					$data_output["history"][$count]["price"] = $row->price;
					$count++;
				}
				if($count == 0)				$data_output['history'] = "";
			}
		}
		
		$providerid = $this->input->post('providerId');
		
		$query = $this->db->query("SELECT COUNT(*) AS voterCount FROM rating WHERE providerId = ".$userid);
		$row = $query->row();
		$voterCount = $row->voterCount;
		$data_output['viewMoreComments'] = "false";
		$data_output['comments'] = "";
		if($voterCount > 0){
			if($voterCount > 3){
				$data_output['viewMoreComments'] = "true";
			}
			$count = 0;
			$query = $this->db->query("SELECT reviewerId, u.`name`, u.avatar, u.lastUpdatedAvatar, rateValue, `comment` FROM rating r JOIN `user` u ON u.id=r.reviewerId WHERE providerId = ".$userid." AND rateValue > 0 AND `comment` IS NOT NULL AND `comment` <> '' LIMIT 3");
			$row = $query->row();
			if($query->num_rows() < 1 || $voterCount < 1){
				$data_output['comments'] = "";
			}else{
				foreach($query->result() as $row){
					$data_output['comments'][$count]['reviewerId'] = $row->reviewerId;
					$data_output['comments'][$count]['name'] = $row->name;
					$data_output['comments'][$count]['avatar'] = $row->avatar;
					$data_output['comments'][$count]['lastUpdatedAvatar'] = $row->lastUpdatedAvatar;
					/*$data_output['rating'][$count]['rateValue'] = ''.$row->rateValue;*/
					$data_output['comments'][$count]['comment'] = $row->comment;
					$count++;
				}
				if($count == 0)				$data_output['comments'] = "";
			}
		}
		
		$query = $this->db->query("SELECT `comment`, rateValue FROM rating  WHERE providerId = ".$userid." AND reviewerId = ".$myid." LIMIT 1");
		$row = $query->row();
		if($query->num_rows() < 1){
			$data_output['myRating'] = "";
		}else{
			$data_output['myRating'][0]['rateValue'] = ''.$row->rateValue;
			$data_output['myRating'][0]['comment'] = $row->comment;
		}

		// header('Content-Type: application/json');
		// echo json_encode($data_output);
		return $data_output;
	}

	function update(){
		$data_output['success'] = "false";
		$error = 0;
		$userid = $this->input->post('userId');

		$phoneNumber = $this->input->post('phoneNumber');
		if($error == 0 && $phoneNumber!=NULL){
			$query_phoneNumber = $this->db->query("SELECT COUNT(phoneNumber) AS count FROM `userprofile` WHERE phoneNumber = '".$phoneNumber."' AND `idUser` NOT LIKE ".$userid);
			$row_phoneNumber = $query_phoneNumber->row();
			if($row_phoneNumber->count > 0)				$error = 1;
		}

		$email = $this->input->post('email');
		if($error == 0 && $email!=NULL){
			$query_email = $this->db->query("SELECT COUNT(email) AS count FROM `userprofile` WHERE email = '".$email."' AND `idUser` NOT LIKE ".$userid);
			$row_email = $query_email->row();
			if($row_email->count > 0)				$error = 2;
		}

		if($error == 0){
			$input_data = array(
				'name' => $this->input->post('name'),
				'lastUpdated' => date("Y-m-d H:i:s"),
			);
			if($this->input->post('password')){
				$password = $this->input->post('password');
				if($password != '' || $password == null){
					$input_data = array(
						'name' => $this->input->post('name'),
						'password' => $password,
						'lastUpdated' => date("Y-m-d H:i:s"),
					);
				}
			} 
			$this->db->where('id', $userid);
			$this->db->update('user', $input_data);
		}

		if($error == 0){
			$input_data = array(
				'phoneNumber' => $this->input->post('phoneNumber'),
				'bio' => $this->input->post('bio'),
				'address' => $this->input->post('address'),
				'licenseNumber' => $this->input->post('licenseNumber'),
				'motorDesc' => $this->input->post('motorDesc'),
				'motorYear' => $this->input->post('motorYear'),
				'email' => $this->input->post('email'),
			);
			$this->db->where('idUser', $userid);
			$this->db->update('userprofile', $input_data);
		}

		if($error == 0){
			$data_output['success'] = "true";
		}else{
			$data_output['error'] = "".$error;
		}
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}

	function changePassword(){
		$input_data = array(
			'password' => $this->input->post('password'),
			'lastUpdated' => date("Y-m-d H:i:s"),
		);
		$this->db->where('id', $this->input->post('userId'));
		$this->db->update('user', $input_data);
		if($this->db->affected_rows() < 1)			$data_output['success'] = "false";
		else			$data_output['success'] = "true";
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}
	
	function changeAvatar(){
		$data_output['success'] = "false";
		$file = 'avatar';
		$userid = $this->input->post('userId');
		$config['upload_path'] = 'avatar/';
		$config['allowed_types'] = '*';
		$config['overwrite'] = TRUE;
		$config['file_name'] = $userid;
		$config['max_size']	= '2048';
		$this->load->library('upload', $config);
		if($this->upload->do_upload($file)) // if upload success
		{
			$result = $this->upload->data();
			foreach($result as $item => $value){
				$filename = $result['file_name'];
				$this->make_thumb($result['file_path'].$filename, $config['upload_path'].$config['file_name'].'t'.$result['file_ext'], 150, 150);
			}
			$input_data = array(
				'avatar' =>  $config['file_name'].'t'.$result['file_ext'],
				'lastUpdatedAvatar' => date("Y-m-d H:i:s"),
			);
			$this->db->where('id', $userid);
			$this->db->update('user', $input_data);
			$data_output['success'] = "true";
		}
		else{
			$data_output['debugfile'] = $this->upload->do_upload($file);
			$data_output['debugid'] = $userid;
		}
			
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}

	function changeAvatarMotor(){
		$data_output['success'] = "false";
		$file = 'avatarmotor';
		$userid = $this->input->post('userId');
		$config['upload_path'] = 'motor/';
		$config['allowed_types'] = '*';
		$config['overwrite'] = TRUE;
		$config['file_name'] = $userid;
		$config['max_size']	= '2048';
		$this->load->library('upload', $config);
		if($this->upload->do_upload($file)) // if upload success
		{
			$result = $this->upload->data();
			foreach($result as $item => $value){
				$filename = $result['file_name'];
				$this->make_thumb($result['file_path'].$filename, $config['upload_path'].$config['file_name'].'t'.$result['file_ext'], 150, 150);
			}
			$input_data = array(
				'avatarMotor' => $config['file_name'].'t'.$result['file_ext'],
				'lastUpdatedAvatarMotor' => date("Y-m-d H:i:s"),
			);
			$this->db->where('idUser', $userid);
			$this->db->update('userprofile', $input_data);
			$data_output['success'] = "true";
		}
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}
	
	function make_thumb($src, $dest, $desired_width, $desired_height) {

		/* read the source image */
		//$source_image = imagecreatefromjpeg($src);
		
		//$width = imagesx($source_image);
		//$height = imagesy($source_image);
		
		/* find the "desired height" of this thumbnail, relative to the desired width  */
		//$desired_height = floor($height * ($desired_width / $width));
		
		/* create a new, "virtual" image */
		thumb($src, 't', $desired_width, $desired_height);
		//$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
		
		/* copy source image at a resized size */
		//imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
		
		/* create the physical thumbnail image to its destination */
		//imagejpeg($virtual_image, $dest);
	}
	
	function forgotPassword(){
		$error = 0;
		$data_output['success'] = "false";
		$usernameoremail = $this->input->post('usernameoremail');
		$query_user = $this->db->query("SELECT username,`name`, email FROM `user` u JOIN userprofile p ON u.id=p.idUser WHERE u.username = '".$usernameoremail."' OR p.email = '".$usernameoremail."'");
		if($query_user->num_rows() > 0){
			$result = $query_user->row_array();
			$newPassword = $this->sendNewPassword($result);
			if($newPassword){
				$input_data = array(
					'password' => md5($newPassword),
					'lastUpdated' => date("Y-m-d H:i:s"),
				);
				$this->db->where('username', $result['username']);
				$this->db->update('user', $input_data);

				$data_output['success'] = "true";
			}else{
				$error = 2;
			}
		}else{
			$error = 1;
		}
		if($error > 0)			$data_output['error'] = "".$error;
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}
	
	function sendNewPassword($user){
		$un = $user['username'];
		$name = $user['name'];
		$email = $user['email'];
		$password = $this->system_libs->shuffle_char(6);
		
		$this->load->library('email');
		$config['protocol'] = 'sendmail';
		$config['mailpath'] = '/usr/sbin/sendmail';
		$config['charset'] = 'iso-8859-1';
		$config['wordwrap'] = TRUE;

		$this->email->initialize($config);
		$this->email->from('donotreply@o-jex.com', 'O-JEX');
		$this->email->to($email); 
		
		$this->email->subject('Reset O-JEX Password');
		$this->email->message("
			Hello, " .$name .",
			We've received a password request for your account.
			Here are your profile:
			username : " .$un ."
			email : " .$email ."
			password : " .$password 
			."
			
			O-JEX TEAM
			http://o-jex.com/");	
		
		if($this->email->send())			return $password;
		else			return FALSE;
	}

	function sendEmailForgotPassword($user){
		$config['protocol'] = 'mail';
		$config['mailtype'] = 'html';
		$config['charset'] = 'utf-8';
		$config['charset'] = 'iso-8859-1';
		$config['wordwrap'] = 'TRUE';

		$un = $user['username'];
		$name = $user['name'];
		$email = $user['email'];
		$password = $this->system_libs->shuffle_char(6);

		$this->email->initialize($config);
		$this->email->from('donotreply@someemail.com');
		$this->email->to($email);

		$pesan = "
		Hello, " .$name .",<br/><br/>
		We've received a password request for your account.<br/><br/>
		Here are your profile:<br/>
		username : " .$un ."<br/>
		email : " .$email ."<br/>
		password : " .$password ."<br/><br/>"
		."<br/><br/><strong>OJEX</strong>";

		$this->email->subject('Information Profile');
		$this->email->message($pesan);

		if(!$this->email->send()){
			return false;
		}

		return $password;
	}
	
	function getNameById($userid){
		$query = $this->db->query("SELECT `name` FROM `user`WHERE `id`=".$userid."");
		$row = $query->row();
		return $row->name;
	}
	
	function getAvatarById($userid){
		$query = $this->db->query("SELECT `avatar` FROM `user`WHERE `id`=".$userid."");
		$row = $query->row();
		return $row->avatar;
	}
	
		
	function getLastUpdatedAvatar($userid){
		$query = $this->db->query("SELECT `lastUpdatedAvatar` FROM `user` WHERE `id`=".$userid."");
		$row = $query->row();
		return $row->lastUpdatedAvatar;
	}
	
	function getPickupStatus($myid,$userid){
		$query = $this->db->query("SELECT ts.`status` FROM transactionStatus ts JOIN `transaction` t ON t.id=ts.idTransaction WHERE t.userId=".$myid." AND t.providerId=".$userid." ORDER BY ts.`timeStamp` DESC LIMIT 1");
		if($query->num_rows()>0){
			$row = $query->row();
			if($row->status == "F" || $row->status == "C")			return 'A';
			else			return $row->status;
		}else{
			return 'A';
		}
	}
	
	function checkPassword($username,$password){
		$query = $this->db->query("SELECT `id`,name FROM `user` WHERE username='".$username."' AND password='".$password."'");
		$row = $query->row();
		if($query->num_rows() > 0){
			return TRUE;		
		}
		return FALSE;
	}
	
	function confirmPremium(){
		$data_output['success'] = "false";
		$input_data = array(
			'idUser' => $this->input->post('userId'),
			'date_time' => date("Y-m-d H:i:s"),
		);
		$this->db->insert('confirm', $input_data);
		if($this->db->affected_rows() > 0)		$data_output['success'] = "true";
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}
	
	function gopremium(){
		$error = 0;
		$userId = $this->input->post('userId');
		$username = $this->input->post('username');
		$password = $this->input->post('password1');
		
		if($this->checkPassword($username,$this->input->post('password')) == FALSE){
			$error = 44;// password salah
		}
		
		if($error == 0 && $username!=NULL){
			if($this->checkAvailableUsername($username) == TRUE){
				$query_username = $this->db->query("SELECT COUNT(username) AS count FROM `user` WHERE username = '".$username."' AND `id` NOT LIKE ".$userId);
				$row_username = $query_username->row();
				if($row_username->count > 0)				$error = 3;
			}else{
				$error = 3;
			}
		}
		
		$phoneNumber = $this->input->post('phone');
		if($error == 0 && $phoneNumber!=NULL){
			if($this->checkAvailablePhone($phoneNumber) == TRUE){
				$query_phoneNumber = $this->db->query("SELECT COUNT(phoneNumber) AS count FROM `userprofile` WHERE phoneNumber = '".$phoneNumber."' AND `idUser` NOT LIKE ".$userId);
				$row_phoneNumber = $query_phoneNumber->row();
				if($row_phoneNumber->count > 0)				$error = 1;
			}else{
				$error = 1;
			}
		}

		$email = $this->input->post('email1');
		if($error == 0 && $email!=NULL){
			if($this->checkAvailableEmail($email) == TRUE){
				$query_email = $this->db->query("SELECT COUNT(email) AS count FROM `userprofile` WHERE email = '".$email."' AND `idUser` NOT LIKE ".$userId);
				$row_email = $query_email->row();
				if($row_email->count > 0)				$error = 2;
			}else{
				$error = 2;
			}
		}		
		if($error == 0 && $email!=NULL && $phoneNumber!=NULL && $username!=NULL){
			
			$url = 'http://admin:1234@indobarter.com/api/index.php/api/ojegapi/register';
			$data = array(
				'username' => $this->input->post('username'),
				'name' => $this->input->post('name'),
				'password1' => $this->input->post('password1'),
				'email1' => $this->input->post('email1'),
				'address1' => $this->input->post('address1'),
				'city' => $this->input->post('city'),
				'postal_code' => $this->input->post('postal_code'),
				'phone' => $this->input->post('phone'),
				'website' => $this->input->post('website'),
				'aboutme' => $this->input->post('aboutme'),
				'dob' => $this->input->post('dob')
			);
		
			$options = array(
				'http' => array(
					'method'  => 'POST',
					'content' => json_encode( $data ),
					'header'=>  "Content-Type: application/json\r\n" .
					"Accept: application/json\r\n"
				)
			);

			$context  = stream_context_create( $options );
			$result = file_get_contents( $url, true, $context );
			$response = json_decode( $result , true);
			if(strcmp ($response['status'], 'success') == 0){
				
				$input_data = array(
					'phoneNumber' => $this->input->post('phone'),
					'email' => $this->input->post('email1'),
					'address' => $this->input->post('address1'),
					'bio' => $this->input->post('aboutme'),
				);
				$this->db->where('idUser', $userId);
				$this->db->update('userprofile', $input_data);
				
				$input_data = array(
					'username' => $this->input->post('username'),
					'no_rekening' => $this->input->post('phone'),
					'premium_pass' => $this->input->post('password1'),
					'lastUpdated' => date("Y-m-d H:i:s"),
					'isPremium' => 2,
				);
				$this->db->where('id', $userId);
				$this->db->update('user', $input_data);
				
				if($this->db->affected_rows() > 0 ){
					$data_output['success'] = "true";
					header('Content-Type: application/json');
					echo json_encode($data_output);
				}
			}else{
				$data_output['success'] = "false";
				header('Content-Type: application/json');
				echo json_encode($data_output);
			}
		
		}else{
			$data_output['success'] = "false";
			$data_output['error'] = "".$error;
			header('Content-Type: application/json');
			echo json_encode($data_output);
		}
		
	}

	
	function checkAvailableUsername($username){
		
		$url = 'http://indobarter.com/api/index.php/api/ojegapi/cekusername/username/'.$username;
		
		$options = array(
			'http' => array(
				'header'=>  "Content-Type: application/json\r\n" .
				"Accept: application/json\r\n"
			)
		);

		$context  = stream_context_create( $options );
		$result = file_get_contents( $url, true, $context );
		$response = json_decode( $result , true);
		if(!empty($response['status']))			return true;
		else			return false;
	
	}
	
	function checkAvailableEmail($email){
		
		$url = 'http://indobarter.com/api/index.php/api/ojegapi/cekemail/emailid/'.str_replace($email, '@', '/server/');
		
		$options = array(
			'http' => array(
				'header'=>  "Content-Type: application/json\r\n" .
				"Accept: application/json\r\n"
			)
		);

		$context  = stream_context_create( $options );
		$result = file_get_contents( $url, true, $context );
		$response = json_decode( $result , true);
		if(!empty($response['status']))			return true;
		else			return false;
	
	}
	
	function checkAvailablePhone($phone){
		
		$url = 'http://indobarter.com/api/index.php/api/ojegapi/ceknorekening/norekening/'.$phone;
		
		$options = array(
			'http' => array(
				'header'=>  "Content-Type: application/json\r\n" .
				"Accept: application/json\r\n"
			)
		);

		$context  = stream_context_create( $options );
		$result = file_get_contents( $url, true, $context );
		$response = json_decode( $result , true);
		if(!empty($response['status']))			return true;
		else			return false;
	
	}

	function getNotification(){
		$data_output['success'] = "true";
		$data_output['notifications'] = "";
		$query = $this->db->query("SELECT DISTINCT n.id AS notification_id, n.need_response, s.`status`,s.timeStamp, t.* FROM notifications n JOIN transactionStatus s ON n.transactionStatusId=s.id JOIN `transaction` t ON s.idTransaction=t.id WHERE n.status = 0 AND n.userId = ".$this->input->post('userId'));
		if($query->num_rows() > 0){
			$row_notif = $query->row(); 
			$count = 0;
			foreach($query->result() as $row_notif){
				if($row_notif->userId > 0 && $row_notif->providerId > 0){
					$data_output['notifications']['transaction'][$count]['notification_id'] = $row_notif->notification_id;
					$data_output['notifications']['transaction'][$count]['timeStamp'] = $row_notif->timeStamp;
					$data_output['notifications']['transaction'][$count]['need_response'] = $row_notif->need_response;
					$data_output['notifications']['transaction'][$count]['idTransaction'] = $row_notif->id;
					$data_output['notifications']['transaction'][$count]['userId'] = $row_notif->userId;
					$data_output['notifications']['transaction'][$count]['userName'] = $this->getNameById($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['userAvatar'] = $this->getAvatarById($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['userLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->userId);
					$data_output['notifications']['transaction'][$count]['providerId'] = $row_notif->providerId;
					$data_output['notifications']['transaction'][$count]['providerName'] = $this->getNameById($row_notif->providerId);
					$data_output['notifications']['transaction'][$count]['providerAvatar'] = $this->getAvatarById($row_notif->providerId);
					$data_output['notifications']['transaction'][$count]['providerLastUpdatedAvatar'] = $this->getLastUpdatedAvatar($row_notif->providerId);
					if($row_notif->need_response == 1){
						$data_output['notifications']['transaction'][$count]['departTime'] = $row_notif->departTime;
						$data_output['notifications']['transaction'][$count]['source_label'] = $row_notif->source_label;
						$data_output['notifications']['transaction'][$count]['source_latitude'] = $row_notif->source_latitude;
						$data_output['notifications']['transaction'][$count]['source_longitude'] = $row_notif->source_longitude;
						$data_output['notifications']['transaction'][$count]['destination_label'] = $row_notif->destination_label;
						$data_output['notifications']['transaction'][$count]['destination_latitude'] = $row_notif->destination_latitude;
						$data_output['notifications']['transaction'][$count]['destination_longitude'] = $row_notif->destination_longitude;
					}
					$data_output['notifications']['transaction'][$count]['price'] = $row_notif->price;
					$data_output['notifications']['transaction'][$count]['paymentMethod'] = $row_notif->paymentMethod;
					$data_output['notifications']['transaction'][$count]['status'] = $row_notif->status;
					$count++;
				}
			}	
		}
		$query_premium = $this->db->query("SELECT * FROM notifications WHERE type LIKE 'P' AND status = 0  AND userId =  ".$this->input->post('userId'));
		if($query_premium->num_rows() > 0){
			$row_premium = $query_premium->row(); 
			$data_output['notifications']['premium'][0]['notification_id'] = $row_premium->id;
			$data_output['notifications']['premium'][0]['need_response'] = $row_premium->need_response;
			$data_output['notifications']['premium'][0]['userId'] = $row_premium->userId;
			$data_output['notifications']['premium'][0]['userName'] = $this->getNameById($row_premium->userId);
		}
		header('Content-Type: application/json');
		echo json_encode($data_output);
	}
	
}